<template>
  <div class="mark-card">
    <div class="addr-poi" v-if="flag == 'add-mark'">
      <div class="title">
        <i>选择打卡地点</i>
      </div>
      <div class="list scroll-base">
        <div class="item" v-for="item in addressList" :key="item.id">
          <b :class="item.selected?'selected':''" @click="itemSelect(item.id)">{{item.title}}</b>
          <ab-button v-if="item.selected" type="hw-warning" @click="selectDone(item)">确认选择</ab-button>
          <i>{{item.address}}</i>
        </div>
      </div>
    </div>
    <div class="mark-info" v-if="flag == 'mark-info'">
      <div class="close-btn" @click="selectDone('close')">
				<i class="iconfont icon-guanbi" style="color: #999;"></i>
			</div>
      <div class="items" v-for="item,index in markInfo" :key="item.id">
        <div class="item" v-if="currentIndex == index">
          <div class="img">
            <div class="img-img" v-if="item.img">
              <img :src="item.img" @click="showImg(item)"/>
              <i class="iconfont icon-shanchu del" @click="msgAction('img',item)"></i>
            </div>
            <div class="img-btn" v-else>
              <i class="iconfont icon-tupian_huaban"></i>
              <input class="img-file" type="file" accept="image/*" @change="imgChange($event,item._id)" />
            </div>
          </div>
          <div class="info">
            <div class="text">
              <b>{{item.title}}</b>
              <i>{{item.address}}</i>
              <i>{{item.selected?'选择打卡时间':item.markTime}}</i>
              <ab-dinput v-if="item.selected" type="datetime-local" v-model:value="item.markTime" color="primary"/>
            </div>
            <div class="btn">
              <ab-button v-if="item.selected" type="primary" @click="createMark">添加记录</ab-button>
              <ab-button v-if="!item.selected" type="error" @click="msgAction('mark',item)">删除记录</ab-button>
              <ab-button v-if="!item.selected" type="success" @click="setMark('UPDATE_IMG',item)">修改图片</ab-button>
            </div>
          </div>
          <div class="pages no-select" v-if="markInfo.length>1">
            <u v-if="currentIndex>0" @click="currentIndex--">上一页</u>
            <i v-else style="opacity: 0;">占位占位</i>
            <i>{{currentIndex+1}}/{{markInfo.length}}</i>
            <u v-if="currentIndex<markInfo.length-1" @click="currentIndex++">下一页</u>
            <i v-else style="opacity: 0;">占位占位</i>
          </div>
        </div>  
      </div>
    </div>
    <ab-msgbox ref="AB_MSG" :title="msgInfo.title" :msg="msgInfo.msg" :type="msgInfo.type" @confirm="msgAction('done')"/>
  </div>
</template>

<script>
import { nextTick, onMounted, reactive, ref } from '@vue/runtime-core'
import util from '@/assets/js/util'
import http from '@/axios/http'
import AbButton from '../able_mod/AbButton.vue'
import AbDinput from '../able_mod/AbDinput.vue'
import $tip from '../able_mod/AbToolTip'
import AbMsgbox from '../able_mod/AbMsgbox.vue'
export default {
  components: { AbButton, AbDinput, AbMsgbox },
  props: ['data'],
  setup(props,ctx) {
    onMounted(()=>{
      flag.value = props.data.flag
      if (flag.value == 'add-mark') getAddr(props.data)
      if (flag.value == 'mark-info') markInit(props.data.markers)
    })
    let flag = ref('')
    // 获取坐标附近地址列表
    let addressList = ref()
    async function getAddr(e) {
      let g = {}
			g.lat = e.latLng.lat
			g.lng = e.latLng.lng
      // g= {lat: 41.777813, lng: 123.436741}
			let _markcoord = localStorage.getItem('markcoord')
      if (_markcoord) _markcoord = JSON.parse(_markcoord)
			if (_markcoord && g.lat == _markcoord.lat && g.lng == _markcoord.lng) {
				addressList.value = JSON.parse(localStorage.getItem('address'))
				return
			}
			let url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${g.lat},${g.lng}&key=${util.TMAP_KEY}&get_poi=1`
      let r = await http.jsonpAction(url)
      if (r.status == 0 && r.message == 'query ok') {
        if (r.result) {
          addressList.value = r.result.pois || []
          localStorage.setItem('address',JSON.stringify(addressList.value))
          localStorage.setItem('markcoord',JSON.stringify(g))
        }
      } else {
        let _msg = r.message || '地址列表查询失败'
        $tip.message.open(_msg,2000,'warning')
      }
    }
    // 选择地址
    function itemSelect(id) {
      let a = addressList.value
      for (let i in a) {
        a[i].selected = false
        if (id == a[i].id) {
          a[i].selected = true
        }
      }
      addressList.value = a
    }
    // 确认选择地址&关闭markcard
    function selectDone(e) {
      ctx.emit('selectaddr', e)
    }
    // mark-card初始化
    let markInfo = ref()
    let currentIndex = ref(0)
    function markInit(e) {
      if (e.selected) {
        let p = {}
        p.openId = e.userOid
        p.lat = e.location.lat
        p.lng = e.location.lng
        p.title = e.title
        p.address = e.address
        p.markTime = util.formatDateTime(new Date()).split('.')[0]
        p.selected = true
        e = []
        e.push(p)
      } else {
        for(let i in e) {
          e[i].img = e[i].imgs && e[i].imgs[0] ? e[i].imgs[0].img : ''
        }
      }
      markInfo.value = e
    }
    // 选择打卡图片
    async function imgChange(e,id) {
      let f = e.target.files[0]
      // console.log(f)
      if (!f) return
      if (f.size > 1000*1024) {
        $tip.message.open('图片不能大于1MB',1500,'error')
      } else {
        let r = await util.fileToBase64(f)
        if (r.indexOf('data:image/') >= 0) {
          let m = markInfo.value
          for(let i in m) {
            if (id == m[i]._id) {
              m[i].img = r
            }
          }
          markInfo.value = m
        } else $tip.message.open('无效的图片格式',1500,'error')
      }
    }
    // 创建打卡记录
    async function createMark() {
      let e = markInfo.value[0]
      let p = {}
			p.openId = e.openId
			p.lat = e.lat
			p.lng = e.lng
			p.title = e.title
			p.address = e.address
			if (e.img) p.imgs = [{img: e.img}]
      p.markTime = e.markTime
			let r = await http.createMark(p)
      if (r.code == 10000) {
        ctx.emit('markdone', r.data)
      }
      
    }
    // 删除打卡记录/修改打卡图片
    async function setMark(f,e) {
      let p = {}
      p.openId = e.openId
      p.recId = e._id
			p.flag = f
      if (f == 'UPDATE_IMG') p.imgs = [{img: e.img}]
      let r = await http.setMark(p)
      if (r.code == 10000) {
        if (f == 'DEL_MARK') 
          ctx.emit('markdone', r.data)
        else 
          ctx.emit('selectaddr', 'close')  
      }
    }
    // 删除确认
    let AB_MSG = ref(null)
    let msgInfo = reactive({
      flag: '',
      title: '',
      msg: '',
      type: ''
    })
    let currentItem = null
    function msgAction(f,e) {
      // console.log(f,e)
      if (e) currentItem = e
      if (f == 'done') {
        if (msgInfo.flag == 'img') {
          let m = markInfo.value
          for(let i in m) {
            if (currentItem._id == m[i]._id) {
              m[i].img = ''
            }
          }
          markInfo.value = m
        }
        if (msgInfo.flag == 'mark') {
          setMark('DEL_MARK',currentItem)
        }
        AB_MSG.value.close()
      } else {
        if (f == 'img') {
          msgInfo.msg = '是否确认删除图片'
        }
        if (f == 'mark') {
          msgInfo.msg = '是否确认删除打卡记录'
        }
        msgInfo.title = '删除操作'
        msgInfo.type = 'error'
        msgInfo.flag = f
        AB_MSG.value.open()
      }
    }
    // 点击查看原图
		function showImg(e) {
			util.showRealImg(e.img,e.title)
		}

    return{
      flag,addressList,itemSelect,selectDone,
      currentIndex,markInfo,imgChange,createMark,setMark,AB_MSG,msgInfo,msgAction,showImg
    }
  }
}
</script>

<style lang="scss" scoped>
.mark-card{
  display: block;
  .addr-poi{
    .title{
      @extend %view-flex;
      height: 45px;
      background-color: $color-footmark;
      i{
        font-style: normal;
        color: #fff;
      }
    }
    .list{
      height: calc(100vh - 45px);
      overflow-y: auto;
      overflow-x: hidden;
      padding: 15px;
      .item{
        @extend %view-flex;
        align-items: flex-start;
        padding: 10px;
        border-bottom: 1px solid #eee;
        b{
          cursor: pointer;
          margin-bottom: 3px;
          color: #666;
        }
        .selected{
          color: $color-footmark;
        }
        i{
          font-style: normal;
          font-size: 14px;
          color: #999;
        }
        button{
          border: 1px solid $color-footmark;
          // color: $color-footmark;
        }
        button:hover{
          color: #fff;
          background-color: $color-footmark;
        }
      }
    }
  }

  .mark-info{
    margin-top: -200px;
    position: relative;
    .close-btn{
      position: absolute;
      top: 0;right: 0;
      cursor: pointer;
      padding: 2px 4px;
      padding-right: 6px;
      z-index: 1;
    }
    .items{
      .item{
        @extend %view-flex;
        flex-direction: row;
        padding: 20px;
        position: relative;
        .img{
          @extend %view-flex;
          width: 180px;
          height: 240px;
          .img-img{
            width: 100%;
            height: 100%;
            position: relative;
            img{
              width: 100%;
              height: 100%;
              object-fit: cover;
              cursor: pointer;
            }
            .del{
              position: absolute;
              bottom: 0;right: 0;
              padding: 10px;
              font-size: 18px;
              background-color: rgb(160,160,160,0.5);
              cursor: pointer;
              color: $color-red;
            }
          }
          .img-btn{
            @extend %view-flex;
            position: relative;
            width: 60%;height: 60%;
            border: 1px solid #eee;
            font-size: 32px;
            color: #ccc;
            cursor: pointer;
            .img-file{
              position: absolute;
              top: 0;left: 0;
              width: 100%;height: 100%;
              opacity: 0;
              cursor: pointer;
            }
          }
          
        }
        .info{
          @extend %view-flex;
          align-items: center;
          justify-content: space-between;
          max-width: 240px;
          min-height: 200px;
          padding: 10px 20px;
          position: relative;
          
          .text{
             @extend %view-flex;
             align-items: flex-start;
             b{
              color: #333;
            }
            i{
              margin-top: 8px;
              font-style: normal;
              font-size: 14px;
              color: #999;
            }
          }
          .btn{
            @extend %view-flex;
            flex-direction: row;
            width: 100%;
            padding: 10px;
          }
        }
        .pages{
          position: absolute;
          bottom: 10px;left: 235px;
          
          i{
            font-style: normal;
            color: #333;
          }
          u{
            cursor: pointer;
            padding: 10px;
            color: #999;
          }
        }
      }
    }
  }
}
</style>